

if("`c(os)'"=="Windows"){
	local tableSaveDir = "Tables\"
	local plotSaveDir = "Plots\NeighborAnalysis\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "Tables/"
	local plotSaveDir = "Plots/NeighborAnalysis/"
	local pythonSaveDir = "PythonScripts/"
}


//Execute python script to find the appropriate changes in treated neighbor states and add variable "delNeighborNoSafety"
python script "`pythonSaveDir'addNeighboringStateVariables.py"

//Establish Control Variable Sets
local Spec1Controls = "c.normYear#i.stateGroup c.quadYear#i.stateGroup asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local Spec2Controls = "`Spec1Controls' i.transactionDataDummy"
local Spec3Controls = "`Spec2Controls' i.regDummyExtSpec3"
local Spec4Controls = "`Spec2Controls' i.regDummyExtSpec4"

//Establish Cluster Variable
local clusterVar = "stateGroup year"

//Absorb Vars are always time and state fixed effects
local absorbVars = "ib51.stateGroup ib1995.year"

//Event Study Table format
local fmtEventStudy = `"cells(b(fmt(3) star) se(par fmt(3))) keep(*neighborDummy*  *shiftedBoundRelYear*) nocon label compress longtable mtitles("\makecell{No \\ DSCs}" "\makecell{Documented \\ DSCs}" "\makecell{Suspected \\ DSCs}" "\makecell{Potential \\ DSCs}") starlevels(* 0.1 ** 0.05 *** 0.01) addnotes("* p \textless 0.1, ** p \textless 0.05, *** p \textless 0.01" "Note: All models include state and year fixed effects as well as state-level time trends." "All models cluster standard errors  by state.")"'



//Add Dummy Variables for Spec2 state Event Study
//Define +- bounds for event study
local bound = 6
//Define Bounds
local lowerBound = -`bound'
local upperBound = `bound'

//Define the relative time period that we will use
local relYear = -1

//Determine the dummy index of the relative year
local relIndex = 1-`lowerBound'+`relYear'

//Generate New Variable
gen boundRelYear = yearrelativeend
//Enforce Bounds
replace boundRelYear = `lowerBound' if boundRelYear<=`lowerBound'
replace boundRelYear = `upperBound' if boundRelYear>=`upperBound'
replace boundRelYear = . if yearrelativeend==.

replace boundRelYear = -1 if boundRelYear==.
qui tab boundRelYear, gen(boundRelYear)
replace boundRelYear = . if yearrelativeend==.

//For plotting purposes
gen tempx = 5
gen tempx1 = 4.85
gen tempx2 = 5.15
gen tempy = 0

//Create shifted Bounds for the other events (neighboring states changing their policy)
gen shiftedBoundRelYear = boundRelYear - `lowerBound'+1
replace shiftedBoundRelYear = `relIndex' if boundRelYear==.

qui levelsof delNeighborNoSafety
foreach numNeighborState in `r(levels)'{
	if(`numNeighborState'>0){
		qui gen shiftedBoundRelYear`numNeighborState' = `relYear'
		qui levelsof statecode if delNeighborNoSafety==`numNeighborState'
		di "`numNeighborState'"
		foreach tempSC in `r(levels)'{
			qui sum year if statecode=="`tempSC'" & delNeighborNoSafety==`numNeighborState'
			qui replace shiftedBoundRelYear`numNeighborState' = year-`r(min)' if statecode=="`tempSC'"
			qui replace shiftedBoundRelYear`numNeighborState' = `lowerBound' if shiftedBoundRelYear`numNeighborState'<`lowerBound' & statecode=="`tempSC'"
			qui replace shiftedBoundRelYear`numNeighborState' = `upperBound' if shiftedBoundRelYear`numNeighborState'>`upperBound' & statecode=="`tempSC'" 
			qui replace shiftedBoundRelYear`numNeighborState' = shiftedBoundRelYear`numNeighborState' +`bound'+1 if statecode=="`tempSC'"
		}
		qui replace shiftedBoundRelYear`numNeighborState' = `relIndex' if shiftedBoundRelYear`numNeighborState'==`relYear'
	}
}

xtset stateGroup year
gen diffDelNeighborNoSafety = d.delNeighborNoSafety

levelsof statecode if diffDelNeighborNoSafety==2

foreach tempSC in `r(levels)'{
	sum delNeighborNoSafety if statecode=="`tempSC'" & diffDelNeighborNoSafety==2
	local indFromCopy = `r(mean)'
	local indToCopy = `indFromCopy'-1
	replace shiftedBoundRelYear`indToCopy' = shiftedBoundRelYear`indFromCopy' if statecode=="`tempSC'"
}


local finIndex = `upperBound'-`lowerBound'+1
forvalues ind = 1(1)`finIndex'{
	di "`ind'"
	gen neighborDummy`ind' = 0
	
	
	qui sum delNeighborNoSafety
	local numInd = `r(max)'
	
	qui levelsof statecode
	foreach tempSC in `r(levels)'{
		forvalues nInd = 1(1)`numInd'{
			qui sum delNeighborNoSafety if statecode=="`tempSC'"
			if(`nInd'<=`r(max)'){
				qui replace neighborDummy`ind'=neighborDummy`ind'+1 if shiftedBoundRelYear`nInd'==`ind' & statecode=="`tempSC'"
			}
		}
	}
	local trueT = `ind'-`bound'-1
	
	if(`trueT'==`upperBound'){
		label var neighborDummy`ind' "Neighbor Event: t $\geq$ `trueT'"
	}
	else if(`trueT'==`lowerBound'){
		label var neighborDummy`ind' "Neighbor Event: t $\leq$ `trueT'"
	}
	else{
		label var neighborDummy`ind' "Neighbor Event: t = `trueT'"
	}
	
	
}
//Define main event labels
label define shiftedBoundRelYear 1 "Main Event: t $\leq$ -6" 2 "Main Event: t=-5" 3 "Main Event: t=-4" 4 "Main Event: t=-3" 5 "Main Event: t=-2" 6 "Main Event: t=-1" 7 "Main Event: t=0" 8 "Main Event: t=1" 9 "Main Event: t=2" 10 "Main Event: t=3" 11 "Main Event: t=4" 12 "Main Event: t=5" 13 "Main Event: t $\geq$ 6"
label values shiftedBoundRelYear shiftedBoundRelYear

// drop neighborDummy`relIndex' to enforce baseline
replace neighborDummy`relIndex' = 1
drop neighborDummy`relIndex'
drop boundRelYear`relIndex'


// //Plot formats
// local plotFormat = `"vertical yline(0) keep(*neighborDummy*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in Total Registration")"'
// local plotFormat = `"vertical yline(0) keep(*neighborDummy*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Neighbor Removal")"'
//
// local plotFormat = `"vertical yline(0) keep(*neighborDummy*) drop(neighborDummy1 neighborDummy`finIndex') omitted baselevels xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0)) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in Reg.")"'

local plotFormat = `"vertical yline(0) keep(*neighborDummy*) drop(neighborDummy1_res neighborDummy13_res) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in Reg." "relative to {&tau}=-1") xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0))"'

// local plotFormat = `"vertical yline(0) keep(*neighborDummy*) drop(neighborDummy1_* neighborDummy13*) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in Reg." "relative to {&tau}=-1") xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0))"'

local plot_order = "neighborDummy2_res neighborDummy3_res neighborDummy4_res neighborDummy5_res . neighborDummy7_res neighborDummy8_res neighborDummy9_res neighborDummy10_res neighborDummy11_res neighborDummy12_res"

local es_controls = "boundRelYear1 boundRelYear2 boundRelYear3 boundRelYear4 boundRelYear5 boundRelYear7 boundRelYear8 boundRelYear9 boundRelYear10 boundRelYear11 boundRelYear12 boundRelYear13"
local neighbor_es_controls = "neighborDummy1 neighborDummy2 neighborDummy3 neighborDummy4 neighborDummy5 neighborDummy7 neighborDummy8 neighborDummy9 neighborDummy10 neighborDummy11 neighborDummy12 neighborDummy13"
//Run regressions and output results

local title = "Spillover Analysis Event Study Results \label{atab:Spillover`upperBound'}"

// //Neighbor State Analysis
// //Spec1 specification
regFWL logregistrations, `es_controls' `neighbor_es_controls', `Spec1Controls', `absorbVars', `clusterVar', _
coefplot, `plotFormat' ytitle("Proportional Change in Total Registration")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec1Spillover`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec1`upperBound'.png", replace name("Spec1Spillover`upperBound'")
eststo Spec1
// //Spec2 specification
regFWL logregistrations, `es_controls' `neighbor_es_controls', `Spec2Controls', `absorbVars', `clusterVar', _

coefplot, `plotFormat' ytitle("Proportional Change in Total Registration")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec2SpilloverWithTitle`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec2`upperBound'.png", replace name("Spec2SpilloverWithTitle`upperBound'")
graph export "`plotSaveDir'NeighborStateSpec2`upperBound'.pdf", replace name("Spec2SpilloverWithTitle`upperBound'")
eststo Spec2 
//
// //Spec3 specification
regFWL logregistrations, `es_controls' `neighbor_es_controls', `Spec3Controls', `absorbVars', `clusterVar', _
coefplot, `plotFormat' ytitle("Proportional Change in Total Registration")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec3Spillover`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec3`upperBound'.png", replace name("Spec3Spillover`upperBound'")
eststo Spec3
// //Spec4 specification
regFWL logregistrations, `es_controls' `neighbor_es_controls', `Spec4Controls', `absorbVars', `clusterVar', _
coefplot, `plotFormat' ytitle("Proportional Change in Total Registration")  ylabel(-.05 0 .05 .1) ytick(-.05(.01).12) order(`plot_order') name("Spec4Spillover`upperBound'") graphregion(color(white)) plotregion(color(white)) p1(label("With Neighbor Coefficients")) addplot(scatter tempy tempx, color(navy)) color(navy) title("Neighbor Event Coefficients")
graph export "`plotSaveDir'NeighborStateSpec4`upperBound'.png", replace name("Spec4Spillover`upperBound'")
eststo Spec4
//
//
// local plotFormat = `"vertical yline(0) keep(*shiftedBoundRelYear*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Treatment Year") ytitle("Proportional Change in Total Registration")"'
//
// local plotFormat = `"vertical yline(0) keep(*shiftedBoundRelYear*) drop(1.shiftedBoundRelYear 13.shiftedBoundRelYear) omitted baselevels xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0)) xtitle("Years Relative to Inspection Removal") ytitle("Proportional Change in Total Registrations")"'
//
local plotFormat = `"vertical yline(0) keep(*boundRelYear*) drop(boundRelYear1_res boundRelYear13_res) xtitle("Years Relative to Inspection Removal") ytitle("Proportional Change in Total Registrations" "relative to {&tau}=-1") xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0))"'
local es_plot_order = "boundRelYear2_res boundRelYear3_res boundRelYear4_res boundRelYear5_res . boundRelYear7_res boundRelYear8_res boundRelYear9_res boundRelYear10 boundRelYear11_res boundRelYear12_res"
//Main Analysis
//Spec1 specification
regFWL logregistrations, `es_controls', `Spec1Controls', `absorbVars', `clusterVar', _
eststo Spec1Main
coefplot Spec1 Spec1Main, `plotFormat' title("Main Event Coefficients") name("Spec1Comparison`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec1`upperBound'.png", replace name("Spec1Comparison`upperBound'")
//Spec2 specification
// reghdfe logregistrations ib`relIndex'.shiftedBoundRelYear `Spec2Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logregistrations, `es_controls', `Spec2Controls', `absorbVars', `clusterVar', _
eststo Spec2Main
coefplot Spec2 Spec2Main, `plotFormat' title("Main Event Coefficients") name("Spec2Comparison`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec2`upperBound'.png", replace name("Spec2Comparison`upperBound'")
// // //Spec2 specification
// reghdfe logregistrations ib`relIndex'.shiftedBoundRelYear `Spec3Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logregistrations, `es_controls', `Spec3Controls', `absorbVars', `clusterVar', _
eststo Spec3Main
coefplot Spec3 Spec3Main, `plotFormat' title("Main Event Coefficients") name("Spec3Comparison`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec3`upperBound'.png", replace name("Spec3Comparison`upperBound'")
// // //Spec2 specification
// reghdfe logregistrations ib`relIndex'.shiftedBoundRelYear `Spec4Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
regFWL logregistrations, `es_controls', `Spec4Controls', `absorbVars', `clusterVar', _
eststo Spec4Main
coefplot Spec4 Spec4Main, `plotFormat' title("Main Event Coefficients") name("Spec4Comparison`upperBound'") p1(label("With Neighbor Coefficients") color(navy) ciopts(color(navy))) p2(label("Without Neighbor Coefficients") color(cranberry) ciopts(color(cranberry))) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(5) size(*.8)) order(`es_plot_order') addplot(scatter tempy tempx1, color(navy) || scatter tempy tempx2, color(cranberry)) 
graph export "`plotSaveDir'NeighborStateMainComparisonSpec4`upperBound'.png", replace name("Spec4Comparison`upperBound'")
//
graph combine Spec1Comparison`upperBound' Spec1Spillover`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateJointSpec1`upperBound'.png", replace
graph combine Spec2Comparison`upperBound' Spec2SpilloverWithTitle`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateJointSpec2`upperBound'.png", replace
graph combine Spec3Comparison`upperBound' Spec3Spillover`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateJointSpec3`upperBound'.png", replace
graph combine Spec4Comparison`upperBound' Spec4Spillover`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) 
graph export "`plotSaveDir'NeighborStateJointSpec4`upperBound'.png", replace
//
//
// if("`c(os)'"=="Windows"){
// 	local tableSaveDir = "Tables\Spillover\"
// 	local plotSaveDir = "Plots\NeighborAnalysis\"
// 	local pythonSaveDir = "PythonScripts\"
// }
// else{
// 	local tableSaveDir = "Tables/Spillover/"
// 	local plotSaveDir = "Plots/NeighborAnalysis/"
// 	local pythonSaveDir = "PythonScripts/"
// }
//
//
// //Output table
// local saveFile = "`tableSaveDir'"+"NeighborAnalysis`upperBound'.tex"
//
// esttab Spec1 Spec2 Spec3 Spec4 using "`saveFile'", `fmtEventStudy' title(`title') replace

drop tempx tempy tempx1 tempx2
